<?php

namespace IDock\Insurance\ZSIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\ZSIC\Response\AllZSICResponse;
use IDock\Insurance\ZSIC\ZSICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllZSICResponse
{

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    public function resolve(): Response
    {
        $body = $this->getBody();
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $errorMsg = $body['head']['resultCode'] ?? '';
            $message = $body['head']['errorMsg'] ?? '';

            $this->getRepeatData($message);
            if ($this->printer->repeatInsuredFlg) {
                return $this;
            }

            $this->setBody($body);
            if ($errorMsg != '1') {
                $this->setError(($errorMsg ?: '') . ":" . $message);
                return $this;
            }
        }
        return $this;
    }

    public function printerInit(): Response
    {
        $body = $this->getBody()['body'] ?? [];
        $data = $body['base'] ?? [];
        //询价流程号
        $orderPrice = 0;
        $this->printer->argc['quotationNo'] = $data['quotationNo'] ?? '';
        $this->printer->inquiryNo = $data['quotationNo'] ?? '';
        $this->printer->argc['businessNo'] = $this->getBody()['head']['businessNo'] ?? '';
        $this->printer->argc['cInspectClaim'] = $data['cInspectClaim'] ?? '';
        if(!empty($this->printer->argc['cInspectClaim'])){
            $this->printer->validateCar = true;
        }
        //车船税
        if ($carShipTax = $body['tax'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['totalTax'] ?? 0;
            $this->printer->carTaxPrinter->overdue = $carShipTax['lateFee'] ?? '';
            $this->printer->carTaxPrinter->payBackTax = $carShipTax['previousPay'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax['taxActual '] ?? '';
            $orderPrice += ($this->printer->carTaxPrinter->carShipTax ?: 0);
        }
        //商业险
        $this->printer->biPremiumPrinter = new PremiumBIPrinter();
        $this->printer->biPremiumPrinter->biStartData = $data['vciEffectiveDate'] ?? '';
        $this->printer->biPremiumPrinter->biEndData = $data['vciExpiryDate'] ?? '';
        $this->printer->biPremiumPrinter->biPremium = $data['vciPremium'] ?? '';
        $this->printer->biPremiumPrinter->biDiscount = $data['vciDiscount'] ?? '';
        $this->printer->biPremiumPrinter->biBasePremium = $data['vciBasePremium'] ?? '';
        $orderPrice += floatval($this->printer->biPremiumPrinter->biPremium);
        if(!empty($this->printer->biPremiumPrinter->biPremium)){
            $this->printer->argc['vciPremium'] = $this->printer->biPremiumPrinter->biPremium;
        }
        //浮动信息
        $this->printer->ncdFactor = $data['ncdRate'] ?? '';
        $this->printer->premiumFactorPrinter->ComFactorAppend('出险次数', 'claimAmount', $data['claimAmount'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('交通违法次数', 'trafficIllegalAmount', $data['trafficIllegalAmount'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主渠道系数', 'channelRate', $data['channelRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主核保系数', 'uwRate', $data['uwRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('交通违法系数', 'illegalRate', $data['illegalRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('商业险保费折扣调整范围下限', 'minVciDiscount', $data['minVciDiscount'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('无赔优待级别', 'claimAdjustLevel', $data['claimAdjustLevel'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数', 'pricingRate', $data['pricingRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数调整范围下限', 'minPricingRate', $data['minPricingRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数调整范围上限', 'maxPricingRate', $data['maxPricingRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('整车风险定价评分', 'riskPriceScore', $data['riskPriceScore'] ?? '');
        $loyalty = ['0' => '新', '1' => '续', '2' => '转'];
        $this->printer->premiumFactorPrinter->ComFactorAppend('交强险忠诚度', 'CIRenewalType', $loyalty[$data['cBusTypeJq'] ?? ''] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('商业险忠诚度', 'BIRenewalType', $loyalty[$data['cBusTypeSy'] ?? ''] ?? '');

        //交强险
        $this->printer->ciPremiumPrinter->ciPremium = $data['tciPremium'] ?? '';
        $this->printer->ciPremiumPrinter->ciDiscount = $data['tciDiscount'] ?? '';
        $this->printer->ciPremiumPrinter->ciStartData = $data['tciEffectiveDate'] ?? '';
        $this->printer->ciPremiumPrinter->ciEndData = $data['tciExpiryDate'] ?? '';
        $this->printer->ciPremiumPrinter->ciBasePremium = $data['tciBasePremium'] ?? '';
        $orderPrice += floatval($this->printer->ciPremiumPrinter->ciPremium);
        if(!empty($this->printer->ciPremiumPrinter->ciPremium)){
            $this->printer->argc['tciPremium'] = floatval($this->printer->ciPremiumPrinter->ciPremium + floatval($this->printer->carTaxPrinter->carShipTax));
        }
        if(isset($body['nonVehicleProducts']['ResponseNonVehicleProduct'])){
            $this->printer->argc['nonCarPremium'] = $body['nonVehicleProducts']['ResponseNonVehicleProduct']['premium'] ?: 0;
            if($this->printer->argc['nonCarPremium'] > 0){
                $orderPrice += floatval($this->printer->argc['nonCarPremium']);
            }
        }
        //特约
        $clauses = $body['clauses']['clause'] ?? [];
        $clauses = $this->formatArray($clauses);
        foreach ($clauses as $value) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $value['clauseCode'] ?? '';
            $specialClauses->clauseContent = $value['content'] ?? '';
            $specialClauses->clauseName = $value['clauseName'] ?? '';
            $specialClauses->autoFlag = $value['flag'] == '1' ? 1 : 0;
            if (($value['productCode'] ?? '') == 'GAUTO') {
                $specialClauses->riskType = 'VCI';//商业险
            } else {
                $specialClauses->riskType = 'TCI';//交强险
            }
            $this->printer->specialClausesAppend($specialClauses);
        }

        //险种
        if ($kinds = $body['coverages']['coverage'] ?? []) {
            $kinds = $this->formatArray($kinds);
            foreach ($kinds as $kind) {
                if($kind['coverageCode'] == 'COMPAUTO'){
                    continue;
                }
                $coverage = new PremiumCoveragePrinter();
                $coverage->coverageCode = array_search($kind['coverageCode'], ZSICEnums::$coverageCode, true);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode] ?? '';
                $coverage->premium = $kind['premium'] ?? '';
                $coverage->basePremium = $kind['basePremium'] ?? '';
                $coverage->amount = $kind['limitAmount'] ?? '';
                $this->printer->coverageListAppend($coverage);
            }
        }

        //非车
        if ($body['nonVehicleProducts'] ?? []) {
            $this->printer->nonCarInquiryPrinter = new NonCarInquiryPrinter();

            foreach ($body['accidentPremium'] ?? [] as $value) {

                $single = new NonCarInquirySinglePrinter();
                $single->premium = $value['sumPremium'] ?? '';
                $single->inquiryNo = null;
                $single->amount = $value['insuranceAmount'] ?? '';
                $single->statusCode = 'success';
                $single->planCode = $value['rideRiskCode'] ?? '';

                $this->printer->nonCarInquiryPrinter->totalPremium += $single->premium;
                $this->printer->nonCarInquiryPrinter->noCarInquirySingleAppend($single);
            }
        }
        $this->printer->argc['orderPrice'] = round($orderPrice,2);
        return $this;
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }

            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }

    public function formatArray(array $arr)
    {
        if(empty($arr)) return $arr;
        if(!isset($arr[0])){
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

    public function getRepeatData($errorMeg)
    {
        if (!$errorMeg) {
            return;
        }
        $errorMeg = str_replace('#-#','',$errorMeg);

        if (preg_match('/终保日期 ([\d\s:-]+)/', $errorMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->success = false;
                $this->printer->repeatMessage = $errorMeg;
            }
        }

        if (preg_match('/商业[[\s\S]*保单止期([\d\s:-]+)/', $errorMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->success = false;
                $this->printer->repeatMessage = $errorMeg;
            }
        }
    }
}
